package cn.orange.ch01_array.slidewindow;

import java.util.HashMap;
import java.util.Map;

/**
 * LC76.最小覆盖子串
 */
public class LC76 {
    public String minWindow(String s, String t) {
        Map<Character, Integer> need = new HashMap<>();
        for (char c : t.toCharArray()) {
            need.put(c, need.getOrDefault(c, 0) + 1);
        }
        Map<Character, Integer> window = new HashMap<>();
        int left = 0, right = 0;
        int minLen = s.length() + 1;
        int valid = 0, start = 0;
        while (right < s.length()) {
            char c = s.charAt(right);
            right++;
            if (need.containsKey(c)) {
                window.put(c, window.getOrDefault(c, 0) + 1);
                if (window.get(c).equals(need.get(c))) valid++;
            }
            while (valid == need.size()) {
                if (right - left < minLen) {
                    minLen = right - left;
                    start = left;
                }
                char cl = s.charAt(left);
                if (need.containsKey(cl)) {
                    if (window.get(cl).equals(need.get(cl))) valid--;
                    window.put(cl, window.getOrDefault(cl, 0) - 1);
                }
                left++;
            }
        }
        return minLen > s.length() ? "" : s.substring(start, start + minLen);
    }

    public static void main(String[] args) {
        LC76 alg = new LC76();
        System.out.println(alg.minWindow("ADOBECODEBANC", "ABC"));
        System.out.println(alg.minWindow("a", "a"));
        System.out.println(alg.minWindow("a", "aa"));
    }
}
